import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
// axios 配置
axios.defaults.timeout = 60000;

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

//axios.defaults.baseURL = 'http://192.168.2.142:8080/warnapps/app';

var fileUrl = 'http://192.168.2.142:8080';


//POST传参序列化
axios.interceptors.request.use((config) => {
	if(config.method  === 'post'){
        config.data = qs.stringify(config.data);
	}
	f7.showIndicator();
	console.log("start ajax");
    return config;
},(error) =>{
    return Promise.reject(error);
});

//返回状态判断
axios.interceptors.response.use((res) =>{
	f7.hideIndicator();
    return res.data;
}, (error) => {
	f7.hideIndicator();
	if(error.toString().indexOf('500') > 0){
		f7.alert("服务器错误:500");
	}else{
		f7.alert("网络错误");
	}
	return Promise.reject(error);
});

function fetch(url, params) {
	return new Promise((resolve, reject) => {
	    axios.post(url, params)
	        .then(response => {
	            resolve(response);
	       }).catch(error => {
	            reject(error) ;
	        })
	})
}
function fetchGet(url,params) {
	return new Promise((resolve, reject) => {
	    axios.get(url,{
			params:params
			})
	        .then(response => {
	            resolve(response);
	        }).catch(error => {
	            reject(error) ;
	        })
	})
}

	 /**
     * 加密函数
     * info 加密信息
     */
function rsaKey(info){	
	if(window.location.protocol === 'file:'){
		info += '#' + returnCitySN["cip"] + '#' + device.uuid;
	} else {
		info += '#' + returnCitySN["cip"] + '#' + '564edd5659e';
	}
	
	var rsaKey = new RSAKey();

	rsaKey.setPublic(b64tohex(localStorage.getItem('modulus')), b64tohex(localStorage.getItem('exponent')));
	
	return  hex2b64(rsaKey.encrypt(info));
}


export default {
	/**
	 * 文件地址
	 */
	fileUrl,
	/**
	 * 获取用户手机
	 */
	iduser (iduser){
		return fetch('/getPhoneNum.do' , iduser)
	},
	/**
	 * 获取验证码
	 */
	idcode (idcode){
		return fetch('/sendMessage.do' , idcode)
	},
	/**
	 * 忘记密码修改
	 */
	forgetpwd (forgetpwd){
		return fetch('/framework/saveNewPassword.do' , forgetpwd)
	},
    /**
     * 用户登录
     */
    Login(params) {
        return  new fetch('/common/getPublicKey').then(res => {    	
        	localStorage.setItem('onlyCode' , res.onlyCode);  
        	localStorage.setItem('modulus' , res.modulus);
        	localStorage.setItem('exponent' , res.exponent);		
			var Info =  params.loginName + '#' + params.loginPwd;					
			return fetch('/applogincontr.do' , { onlyCode: res.onlyCode , loginCode : rsaKey(Info) } );
        });
    },
    /**
     * 用户退出
     */
    exitLogin( token ){
    	return fetch('/framework/signOutUser' , { onlyCode: localStorage.getItem('onlyCode') , costoken : rsaKey(token) } );
    },
}

